// 给你一个链表数组，每个链表都已经按升序排列。

// 请你将所有链表合并到一个升序链表中，返回合并后的链表。
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        if(lists.length == 0)
            return null;
        return merge(0,lists.length-1,lists);
    }
    private ListNode merge(int left,int right,ListNode[]lists)
    {
        if(left==right)
            return lists[left];
        int mid = left+(right-left)/2;
        ListNode l1 = merge(left,mid,lists);
        ListNode l2 = merge(mid+1,right,lists);
        return merge2Lists(l1,l2);
    }
    private ListNode merge2Lists(ListNode l1,ListNode l2)
    {
        ListNode l3 = new ListNode(0);
        ListNode tail = l3;
        while(l1!=null&&l2!=null)
        {
            if(l1.val<l2.val)
            {
                tail.next = l1;
                l1 = l1.next;
            }
            else{
                tail.next = l2;
                l2= l2.next;
            }
            tail = tail.next;
        }
        tail.next = l1==null?l2:l1;
        return l3.next;
    }
}